package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.*;
import com.bwie.mapper.TbCarMapper;
import com.bwie.mapper.TbStockMapper;
import com.bwie.service.IOrderService;
import com.bwie.service.TbProductService;
import com.bwie.mapper.TbProductMapper;
import com.bwie.state.PayStateEnum;
import com.bwie.utils.R;
import com.bwie.vo.OrderVo;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.ProductVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_product(商品表)】的数据库操作Service实现
* @createDate 2024-09-25 15:35:07
*/
@Service
public class TbProductServiceImpl extends ServiceImpl<TbProductMapper, TbProduct>
    implements TbProductService{

    @Autowired
    TbProductMapper tbProductMapper;

    @Autowired
    TbCarMapper tbCarMapper;

    @Autowired
    TbStockMapper tbStockMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    IOrderService iOrderService;

    @Override
    public R getProductList(PageInfoVo pageInfoVo) {
        //-- 构造分页
        Page<ProductVo> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //-- 构造查询条件
//        QueryWrapper<TbProduct> wrapper = new QueryWrapper<>();
//        if(!StringUtils.isEmpty(pageInfoVo.getKeyWord())) {
//            wrapper.like("prod_name", pageInfoVo.getKeyWord());
//        }
//        if(pageInfoVo.getBrandId() != null) {
//            wrapper.eq("prod_brand", pageInfoVo.getBrandId());
//        }
//        wrapper.lambda().orderByDesc(TbProduct::getProdId);
        //-- 查询数据
//        Page<TbProduct> tbProductPage = tbProductMapper.selectPage(page, wrapper);
        IPage<ProductVo> productList = tbProductMapper.getProductList(page, pageInfoVo);
        return R.OK(productList);
    }

    @Override
    public R getBrandList() {

        List<TbBrand> brandList = tbProductMapper.getBrandList();

        return R.OK(brandList);
    }

    @Override
    public R addProdToCar(TbProduct tbProduct) {
        // 检查购物车，是否已经添加过了
        TbCar car = tbCarMapper.selectOne(
                new QueryWrapper<TbCar>().lambda().eq(TbCar::getProdId, tbProduct.getProdId()).last("limit 1")
        );
        if(car != null) {
            return R.ERROR(500, "商品已经添加过了，无需重复添加！");
        }

        // 创建购物车对象
        TbCar tbCar = new TbCar();

        // 设置用户id
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        tbCar.setUserId(userId);

        // 设置产品信息
        tbCar.setProdId(tbProduct.getProdId());
        tbCar.setProdName(tbProduct.getProdName());
        tbCar.setCreateTime(new Date());

        tbCarMapper.insert(tbCar);

        return R.OK();
    }

    @Override
    public R addOrder(ArrayList<TbProduct> tbProducts) {
        // 参数判断
        if(tbProducts == null || tbProducts.size() <= 0) {
            return R.ERROR(500, "请选择要购买的商品！");
        }

        //-- 检查库存
        for (TbProduct tbProduct : tbProducts) {
            TbStock tbStock = tbStockMapper.selectOne(new QueryWrapper<TbStock>().lambda().eq(TbStock::getProdId, tbProduct.getProdId()));
            if(tbStock == null) {
                return R.ERROR(500, "产品不存在，无法下单！");
            }
            // 默认购买产品数量为1
            if(tbStock.getProdCount() < 1) {
                return R.ERROR(500, "库存不足，无法下单！");
            }

            //-- 扣减库存后，更新库存
            tbStock.setProdCount(tbStock.getProdCount() - 1);
            tbStockMapper.updateById(tbStock);
        }

        // 获取token
        String token = request.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        // 使用openFeign下单
        OrderVo orderVo = new OrderVo();
        orderVo.setTbProducts(tbProducts);
        orderVo.setUserId(userId);

        return iOrderService.addOrder(orderVo);
    }
}




